package com.example.springbootbook.controller;

import com.example.springbootbook.model.BookInfo;
import com.example.springbootbook.model.PageRequest;
import com.example.springbootbook.model.PageResult;
import com.example.springbootbook.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RequestMapping("/book")
@RestController
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping("/getBookListByPage")
    public PageResult<BookInfo> selectBookInfoByPage(PageRequest pageRequest) {
        log.info("查询翻页信息,pageRequest{}",pageRequest);
        if (pageRequest.getCurrentPage() <= 0 || pageRequest.getPageSize() <= 0) {
            return null;
        }
        PageResult<BookInfo> pageResult = null;
        try {
            pageResult = bookService.selectBookInfoByPage(pageRequest);
            return pageResult;
        }catch (Exception e) {
            log.error("查询翻页信息错误,e:{}",e);
            return null;
        }
    }

    @RequestMapping(value = "addBook", produces = "application/json")
    public String addBook(BookInfo bookInfo) {
        log.info("添加图书,bookInfo{}",bookInfo);
        if (!StringUtils.hasLength(bookInfo.getBookName())
        || !StringUtils.hasLength(bookInfo.getAuthor())
        || !StringUtils.hasLength(bookInfo.getPublish())
        || bookInfo.getPrice()==null
        || bookInfo.getCount()<0) {
            return "参数校验失败，请检查输入的参数";
        }
        Integer result = bookService.addBook(bookInfo);
        if (result <= 0) {
            log.error("添加图书错误:bookInfo{}",bookInfo);
            return "添加图书错误，请联系管理员";
        }

        return "";
    }

    @RequestMapping("/queryBookInfoById")
    public BookInfo queryBookInfoById(@Param("id") Integer id) {
        if (id == null || id <= 0) {
            log.error("通过ID查询书籍出现错误:id{}",id);
        }
        log.info("根据ID查询书籍:id{}",id);
        BookInfo bookInfo = null;
        try {
            bookInfo = bookService.queryBookInfoById(id);
            return bookInfo;
        }catch (Exception e) {
            log.error("通过ID查询书籍出现错误:e{}",e);
            return null;
        }
    }

    @RequestMapping("/updateBook")
    public String updateBook(BookInfo bookInfo) {
        log.info("更新书籍:bookinfo{}",bookInfo);
        Integer result = null;
        try {
            result = bookService.updateBook(bookInfo);
        } catch (Exception e) {
            log.error("更新BookInfo出错:e{}",e);
            return "更新图书出错，请联系管理员";
        }
        if (result == 0) {
            log.error("更新图书失败，请联系管理员");
            return "更新图书失败，请联系管理员";
        }

        return "";
    }
}
